"""
@File    ：get_browser_driver.py
@Author  ：ixiaodu
@Date    ：2024/5/29
@Desc    ：
"""

import os
import shutil
import subprocess
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from webdriver_manager.chrome import ChromeDriverManager


def determine_google_drive():
    """判断谷歌驱动版本是否和谷歌浏览器版本一致"""

    # 指定谷歌驱动目标位置
    folder_path = r'C:\Users\29690\PycharmProjects\Coded_UI_Test\driver'
    # 驱动名称
    file_name = 'chromedriver.exe'
    # 路径拼接
    file_path = os.path.join(folder_path, file_name)

    if os.path.exists(file_path):
        # 获取chromedriver.exe版本(谷歌浏览器驱动)
        result = subprocess.run([file_path, '--version'], capture_output=True, text=True)
        driver_version = '.'.join(result.stdout.strip().split(' ')[1].split('.')[:-1])

        # 获取chrome.exe版本(谷歌浏览器)
        result_a = subprocess.run(
            ['reg', 'query', r'HKEY_CURRENT_USER\Software\Google\Chrome\BLBeacon', '/v', 'version'],
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE,
            text=True)
        chrome_version = '.'.join(result_a.stdout.split('version    REG_SZ    ')[1].split('.')[0:3])

        # 判断版本是否一致，不一致就重新下载
        if driver_version != chrome_version:
            # 使用ChromeDriverManager安装ChromeDriver，并获取驱动程序的路径
            print("版本不一致，正在更新浏览器驱动")
            download_driver_path = ChromeDriverManager().install()
            # 复制文件到目标位置
            shutil.copy(download_driver_path, folder_path)
        else:
            print("版本一致，无需重新下载！")

    else:
        download_driver_path = ChromeDriverManager().install()
        shutil.copy(download_driver_path, folder_path)

    return file_path


if __name__ == '__main__':
    # 创建Chrome WebDriver，并指定驱动路径
    driver = webdriver.Chrome(service=Service(determine_google_drive()))
    # 打开百度网页
    driver.get("https://www.baidu.com")
